// 坐标
class Point {
  public x: number;
  public y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }

  offset(x: number, y: number) {
    return new Point(this.x + x, this.y + y);
  }

  up() {
    return this.offset(0, -1);
  }

  down() {
    return this.offset(0, 1);
  }

  left() {
    return this.offset(-1, 0);
  }

  right() {
    return this.offset(1, 0);
  }
}

type map = [number, number, number][];

class Game {
  map: map;
  static success_map = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 0],
  ];
  successEvent: VoidFunction | null;

  constructor(map: map) {
    this.map = map;
    this.successEvent = null;
  }

  // 点击
  click(point: Point) {
    const u = point.up();
    const p = point.down();
    const l = point.left();
    const r = point.right();

    if (this.is_empty(u)) {
      this.position_change(point, u);
    }

    if (this.is_empty(p)) {
      this.position_change(point, p);
    }

    if (this.is_empty(l)) {
      this.position_change(point, l);
    }

    if (this.is_empty(r)) {
      this.position_change(point, r);
    }
  }

  // 坐标是否为空
  is_empty(point: Point) {
    if (!this.map[point.x]) {
      // 越界
      return false;
    }
    return this.map[point.x][point.y] === 0;
  }

  // 交换位置
  position_change(point1: Point, point2: Point) {
    const v = this.map[point1.x][point1.y];
    this.map[point1.x][point1.y] = this.map[point2.x][point2.y];
    this.map[point2.x][point2.y] = v;
    console.log(this.map);
  }

  // 是否完成
  is_complete() {
    let res: boolean = true;
    for (let i = 0; i < Game.success_map.length; i++) {
      for (let j = 0; j < Game.success_map[i].length; j++) {
        if (Game.success_map[i][j] !== this.map[i][j]) {
          res = false;
          break;
        }
      }
      if (!res) {
        break;
      }
    }
    // 成功回调
    if (res && this.successEvent) {
      this.successEvent();
    }
    return res;
  }

  // 
  addListenSuccess(f: VoidFunction) {
    this.successEvent = f;
  }
}

export { Point, Game };
